import Request, { HttpRequestConfig, HttpTask } from "luch-request";

import { useUserStore } from "@/store/user";
import { baseUrl } from "@/utils/define";

// 创建实例
const http = new Request();

// 请求拦截器
http.interceptors.request.use(
  (config: HttpRequestConfig<HttpTask>) => {
    const token = useUserStore()?.accessToken;
    if (token) {
      if (!config.header) {
        config.header = {};
      }
      config.header.token = token;
    } else if (!config?.custom?.noToken) {
      uni.showModal({
        content: "登录超时，请重新登录",
        success(res) {
          if (res.confirm) {
            uni.removeStorageSync("token");
            uni.removeStorageSync("userInfo");
            uni.navigateTo({
              url: "/pages/login/login",
            });
          }
        },
      });
      return Promise.reject();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    return new Promise((resolve, reject) => {
      const { code, data, msg } = response.data;
      switch (code) {
        case 200:
          resolve(data);
          break;
        case 5001:
          uni.showModal({
            content: "登录超时，请重新登录",
            success(res) {
              if (res.confirm) {
                uni.removeStorageSync("token");
                uni.removeStorageSync("userInfo");
                uni.navigateTo({
                  url: "/pages/login/login",
                });
              }
            },
          });
          reject(response);
          break;
        default:
          uni.showToast({
            title: msg || "网络错误",
            icon: "none",
          });
          reject(response);
      }
    });
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 设置基础URL
http.setConfig((config) => {
  config.baseURL = baseUrl;
  if (!config.header) {
    config.header = {};
  }
  config.header["hxs-userType"] = "user";
  config.header["hxs-terminal"] = "user_app";
  return config;
});

export default http;
